/* 
 *  <copyright file="EventRouterGameService.cs" company="Wesley Jowitt">
 *  
 *  SobrietyEngine: Copyright (c) 2011 Wesley Jowitt
 *  
 *  This software is distributed under a software license.
 *   * As of the creation time of this file, the license in use is the Microsoft Permissive License (Ms-PL) 
 *    * The license can be viewed at:
 *     * License.Txt in the root folder of this project
 *      * http://sobrietyengine.codeplex.com/license
 *       * http://www.microsoft.com/opensource/licenses.mspx
 *       
 *  </copyright>
 *   */

using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;

using SobrietyEngine.Guids;
using SobrietyEngine.Logging;
using SobrietyEngine.Events.Logging;

namespace SobrietyEngine.Events
{
    public class EventRouterGameService:GameComponent, IEventRouter, IEventListener
    {
        public Boolean LogRaisedEvents { get; set; }
        public Boolean LogProcessedEvents { get; set; }
        public List<String> LogEventIgnore { get; set; }

        Dictionary<string, List<IEventListener> > ListenersByType;
        Queue<Event> EventsQueue;
        GameTime CurrentGameTime;
       
        public int EventCount { get { return EventsQueue.Count; } }

        public static Queue<Event> EventPool = new Queue<Event>();
        
        public EventRouterGameService(Microsoft.Xna.Framework.Game game):base(game)
        {
            game.Services.AddService(typeof(IEventRouter), this);
            ListenersByType = new Dictionary<string, List<IEventListener> >();
            //add our 'all events' listener
            ListenersByType.Add("*", new List<IEventListener>());
            EventsQueue = new Queue<Event>();
            LogRaisedEvents = false;
            LogProcessedEvents = false;
            LogEventIgnore = new List<string>();
        }

        public void HandleEvent(Event e)
        {
            if (e.Type == typeof(Logging.LogRaisedEvents))
            {
                LogRaisedEvents = false;
                return;
            }
            
            else if (e.Type == typeof(Logging.LogProcessedEvents))
            {
                LogRaisedEvents = true;
                return;
            }
        }

        public void RegisterEventListeners()
        {
            AddEventListener(typeof(Logging.LogRaisedEvents), this);
            AddEventListener(typeof(Logging.LogProcessedEvents), this);
        }

        public void UnregisterEventListeners()
        {
            RemoveEventListener(this);
        }

        public override void Update(GameTime gameTime)
        {
            CurrentGameTime = gameTime;
            ProcessEvents();
        }

        public void ProcessEvents()
        {
            while (EventsQueue.Count > 0)
            {
                Event e = EventsQueue.Dequeue();
                ProcessEvent(e);
                EventPool.Enqueue(e);
            }
        }

        public void ProcessEvent(Event e)
        {
            if(LogProcessedEvents)
                LogItem(e.Type.ToString(), "Processing > " + e.From + "-" + e.Type.ToString(), LogMessageTypes.EventRaised);

            if (ListenersByType.ContainsKey(e.Type.ToString()))
            {
                List<IEventListener> lbt = new List<IEventListener>(ListenersByType[e.Type.ToString()]);
                int lbtL = lbt.Count;
                for (int el = 0; el < lbtL; ++el)
                {
                    if (lbt[el] != null)
                    {
                        lbt[el].HandleEvent(e);
                    }
                }

                lbt = new List<IEventListener>(ListenersByType["*"]);
                lbtL = lbt.Count;
                for (int el = 0; el < lbtL; ++el)
                {
                    lbt[el].HandleEvent(e);
                }
            }
        }

        public void RaiseEvent(Object raisedBy, IEventData eventData, CGuid from)
        {
            if (EventPool.Count > 0)
            {
                RaiseEvent(EventPool.Dequeue().NewPoolEvent(raisedBy, eventData, from));
            }
            else
                RaiseEvent(new Event(raisedBy, eventData, from));
        }

        public void RaiseEvent(Object raisedBy, IEventData eventData)
        {
            if (EventPool.Count > 0)
            {
                RaiseEvent(EventPool.Dequeue().NewPoolEvent(raisedBy, eventData));
            }
            else
                RaiseEvent(new Event(raisedBy, eventData));
        }

        private void RaiseEvent(Event e)
        {
            if(LogRaisedEvents)
                LogItem(e.Type.ToString(), e.ToString(), LogMessageTypes.EventRaised);
            
            e.Time = CurrentGameTime;
            EventsQueue.Enqueue(e);
        }

        private void RaiseEventNow(Event e)
        {
            if(LogRaisedEvents)
                LogItem(e.Type.ToString(),  e.ToString(), LogMessageTypes.EventRaised);

            e.Time = CurrentGameTime;
            ProcessEvent(e);
        }

        public void ClearEvents()
        {
            EventsQueue.Clear();
        }

        public void ClearEventListeners()
        {
            ListenersByType.Clear(); //this should garbage collect the lists, which will
            //GC the listeners, unless something, somewhere is holding areference (shouldn't)
        }


        public void AddEventListener(Type eventType, IEventListener el)
        {
            String eventTypeString = eventType.ToString();
            if (ListenersByType.ContainsKey(eventTypeString))
            {
                if (ListenersByType[eventTypeString].Contains(el))
                {
                    Logger.GetSingleton().WriteError("Duplicate Listeners for same object: " + el.GetType().ToString());
                    System.Diagnostics.Debug.Assert(false);
                }
                else
                    ListenersByType[eventTypeString].Add(el);
            }
            else
            {
                ListenersByType.Add(eventTypeString, new List<IEventListener>());
                ListenersByType[eventTypeString].Add(el);
            }
        }

        public void RemoveEventListener(IEventListener el)
        {
            foreach (List<IEventListener> l in ListenersByType.Values)
            {
                while(l.Contains(el))
                    l.Remove(el);
            }
            //if (ListenersByType.ContainsKey(el.GetEventType()))
            //    ListenersByType[el.GetEventType()].Remove(el);
        }

        public void RemoveEventListener(Type eventType, IEventListener el)
        {
            if (ListenersByType.ContainsKey(eventType.ToString()))
                ListenersByType[eventType.ToString()].Remove(el);
        }

        public void RemoveEventListener(CGuid guid)
        {
            IEventListener el = (IEventListener)guid.Resolve();
            RemoveEventListener(el);
        }

        private void LogItem(String eventType, String msg, String type)
        {
            if (eventType == typeof(LoggedItem).ToString())
                return;
            if(LogEventIgnore.Contains(eventType))
                return;
            foreach (String s in LogEventIgnore)
            {
                if (eventType.Contains(s))
                    return;
            }

            Logger.GetSingleton().WriteLine(msg, type);
        }


    }
}